import { Component, Emit, Prop, Ref, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import { deleteRole, editRole, getRoleInfo, getRoleMenuTree, getSystemUserList } from '@/api/system'
import type { RoleDto, RoleMenuDto } from '@/api/system/types'
import userStore from '@/stores/user'
import { Button, Input, message, Radio, RadioGroup, Tree } from 'ant-design-vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import type { DataNode } from 'ant-design-vue/es/tree'
import type { AntTreeDto } from '@/api/types'
import { confirm, createAntTreeKey } from '@/utils/util'

@Component
export class RoleDetail extends Render {
    @Prop() roleId!: number

    @Ref treeRef = null as InstanceType<typeof Tree> | null

    roleName = ''
    activeRadio = null as number | null

    roleInfo = {} as RoleDto
    menuData = [] as AntTreeDto<RoleMenuDto>[] 

    checkedKeys = [] as number[]
    sonCheckedKeys = [] as number[]
    allSonCheckedKeys = [] as number[]

    useStore = userStore()

    // get userId() {
    //     return basicStore.
    // }
    @Emit('refresh')
    handleRefresh() {}

    @Watch('roleId')
    async handleWatchRoleId() {
        await this.initRoleData()
        await this.initRoleTreeData()
        this.activeRadio = null
    }

    async initRoleData() {
        const data = await getRoleInfo(this.roleId)
        this.roleInfo = data
        this.roleName = data.roleName
    }

    async initRoleTreeData() {
        const res = await getRoleMenuTree(this.roleId, 2)
        this.checkedKeys = res.checkedKeys
        const data = res.menus.map(i => {
            return {
                key: i.id,
                ...i
            }
        })
        this.menuData = createAntTreeKey<RoleMenuDto>(data, 'id')
        this.sonCheckedKeys = this.getSonKeys(res.menus)
    }

    /**
     * 获取checkedKeys里所有的子节点
     * @param menus
     * @returns
     */
    getSonKeys(menus: RoleMenuDto[]) {
        const res = [] as number[]
        const getSon = (menus: RoleMenuDto[]) => {
            for (const item of menus) {
                if (item.children?.length) {
                    getSon(item.children)
                } else {
                    this.allSonCheckedKeys.push(item.id)
                    if (this.checkedKeys.includes(item.id)) {
                        res.push(item.id)
                    }
                }
            }
        }
        getSon(menus)
        return res
    }

    onRadioChange() {
        if (this.activeRadio === 0) {
            this.sonCheckedKeys = []
        } else {
            this.sonCheckedKeys = this.allSonCheckedKeys
        }
    }

    async onSubmit() {
        // console.log({
        //     roleId: this.roleInfo.roleId,
        //     roleName: this.roleName,
        //     roleKey: this.roleInfo.roleKey,
        //     roleSort: this.roleInfo.roleSort,
        //     status: this.roleInfo.status,
        //     menuIds: this.sonCheckedKeys
        // })
        await editRole({
            roleId: this.roleInfo.roleId,
            roleName: this.roleName,
            roleKey: this.roleInfo.roleKey,
            roleSort: this.roleInfo.roleSort,
            status: this.roleInfo.status,
            menuIds: this.sonCheckedKeys
        })
        message.success('修改成功')
        this.handleRefresh()
    }

    async onRemove() {
        const hint = this.roleInfo.peopleCount ? `（当前角色下有${this.roleInfo.peopleCount}名成员，删除角色后，功能权限自动降级为无，数据权限降级为仅自己，确认删除角色么？` : '确定删除该角色吗？'
        await confirm(hint, '提示')
        // const res = await ElMessageBox.confirm(hint, '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        // })
        // if (res === 'confirm') {
        await deleteRole(this.roleInfo.roleId)
        message.success('删除成功')
        this.handleRefresh()
        // }
    }
    render() {
        return (
            <div class="h-full flex flex-col">
                <div class="py-10px px-16px bg-blue-100 bg-opacity-10">
                    <div class="flex justify-between">
                        <div class="flex items-center">
                            <span class="flex-shrink-0">角色名称：</span>
                            <Input v-model:value={this.roleName}></Input>
                        </div>
                        {this.roleInfo.roleKey === 'saas_operation_role' ? (
                            <></>
                        ) : (
                            <Button icon={h(DeleteOutlined)} type="link"  onClick={this.onRemove}>
                                删除
                            </Button>
                        )}
                    </div>
                </div>
                <div class="bg-white-dark-100 p-16px flex-1 overflow-auto">
                    <div class="flex items-center mb-10px">
                        <div class="mr-20px flex-shrink-0">权限范围</div>
                        <div class="flex items-center">
                            <RadioGroup v-model:value={this.activeRadio} onChange={this.onRadioChange}>
                                <Radio value={1}>全选</Radio>
                                <Radio value={0}>全不选</Radio>
                            </RadioGroup>
                        </div>
                    </div>
                    <div class="flex items-start overflow-auto">
                        <div class="mr-20px flex-shrink-0">选择权限</div>
                        <div class="flex items-center flex-1">
                            <Tree
                                ref="treeRef"
                                class="w-full"
                                treeData={this.menuData}
                                fieldNames={{
                                    title: 'label',
                                    key: 'id'
                                }}
                                checkable
                                v-model:checkedKeys={this.sonCheckedKeys}
                                defaultExpandAll={false}
                                checkStrictly={false}
                            ></Tree>
                        </div>
                    </div>
                </div>
                <div class="text-center mt-10px">
                    <Button type="primary" onClick={this.onSubmit}>
                        确定
                    </Button>
                </div>
            </div>
        )
    }
}

export default toNative<{ roleId: number }, { refresh: () => void }>(RoleDetail)
